package excel

import (
	"context"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/shakinm/xlsReader/xls"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"go-excel-tool/server"
	"log"
	"strings"
)

type ExcelService struct {
	ctx context.Context
}

func NewExcel() *ExcelService {
	return &ExcelService{}
}
func (es *ExcelService) Start(ctx context.Context) {
	es.ctx = ctx
}
func (es *ExcelService) ChooseExcel() server.Result {

	filePath, err := runtime.OpenFileDialog(es.ctx, runtime.OpenDialogOptions{
		Title: "选择文件",
		Filters: []runtime.FileFilter{
			{DisplayName: "表格文件", Pattern: "*.xlsx;*.xls;*.csv"},
		},
	})
	if err != nil {
		return server.Fail(-1, err.Error())
	}

	return server.Success(filePath)
}

func (es *ExcelService) SearchData(filePath, keyword string) server.Result {

	if strings.HasSuffix(filePath, ".xlsx") {
		data := readFromXlsx(filePath, keyword)
		return server.Success(data)
	} else if strings.HasSuffix(filePath, ".xls") {
		data := readFromXls(filePath, keyword)
		if data != nil {
			return server.Success(data)
		}
		return server.Fail(-1, "未找到数据")

	} else if strings.HasSuffix(filePath, "csv") {
		//readFromCsv(filePath)
		return server.Fail(-1, "暂不支持此格式文件")
	}
	return server.Fail(-1, "文件格式错误")
}

func readFromXlsx(filePath, keyword string) map[string]interface{} {

	f, err := excelize.OpenFile(filePath)
	if err != nil {
		log.Println("err ", err)
		return nil
	}
	sheetList := f.GetSheetList()
	returnData := make(map[string]interface{})
	for sheetIndex := range sheetList {
		sheetName := f.GetSheetName(sheetIndex)
		rows, err := f.GetRows(sheetName)

		if err != nil {
			log.Println("GetRows err ", err)
			continue
		}
		var arr [][]string
		//var finalData [][]string
		for _, row := range rows {
			for _, item := range row {
				if strings.Contains(item, keyword) {
					arr = append(arr, row)
				}
			}
		}
		if len(arr) > 0 {
			if len(rows) >= 3 {
				firstRow := rows[0]
				secondRow := rows[1]

				var header []string
				if len(firstRow) > len(secondRow) {
					for _, cel := range firstRow {
						header = append(header, cel)
					}
				} else if len(firstRow) == len(secondRow) {
					firstEntryCount := 0
					secondEntryCount := 0
					for _, cellData := range firstRow {
						if cellData != "" {
							firstEntryCount++
						}
					}
					for _, cellData := range secondRow {
						if cellData != "" {
							secondEntryCount++
						}
					}
					if firstEntryCount >= secondEntryCount {
						for _, cel := range firstRow {
							header = append(header, cel)
						}
					} else {
						for _, cel := range secondRow {
							header = append(header, cel)
						}
					}
				} else {
					for _, cel := range secondRow {
						header = append(header, cel)
					}
				}
				arr = append(arr, header)
			}
			returnData[sheetName] = arr

		}
	}
	if len(returnData) == 0 {
		return nil
	}
	return returnData
}
func readFromXls(filePath, keyword string) map[string]interface{} {
	log.Println("读取xls")
	workbook, err := xls.OpenFile(filePath)
	if err != nil {
		log.Println("err ", err)
	}
	returnData := make(map[string]interface{})
	for _, sheet := range workbook.GetSheets() {
		rows := sheet.GetRows()
		var data [][]string
		for _, row := range rows {
			var rowData []string
			for _, col := range row.GetCols() {
				if strings.Contains(col.GetString(), keyword) {
					for _, cellData := range row.GetCols() {
						rowData = append(rowData, cellData.GetString())
					}
				}
			}
			if len(rowData) > 0 {
				data = append(data, rowData)
			}
		}
		log.Printf("%s %+v", sheet.GetName(), data)
		if len(data) > 0 {
			if len(rows) >= 3 {
				//获取前两行
				firstRow := rows[0]
				secondRow := rows[1]
				var headers []string

				log.Printf("%s len(firstRow.GetCols()) >>> %d", sheet.GetName(), len(firstRow.GetCols()))
				log.Printf("%s len(secondRow.GetCols() >>>>> %d", sheet.GetName(), len(secondRow.GetCols()))
				if len(firstRow.GetCols()) > len(secondRow.GetCols()) {
					for _, cel := range firstRow.GetCols() {
						headers = append(headers, cel.GetString())
					}
				} else if len(firstRow.GetCols()) == len(secondRow.GetCols()) {
					firstEntryCount := 0
					secondEntryCount := 0
					for _, cellData := range firstRow.GetCols() {
						if cellData.GetString() != "" {
							firstEntryCount++
						}
					}
					for _, cellData := range secondRow.GetCols() {
						if cellData.GetString() != "" {
							secondEntryCount++
						}
					}
					if firstEntryCount >= secondEntryCount {
						for _, cel := range firstRow.GetCols() {
							headers = append(headers, cel.GetString())
						}
					} else {
						for _, cel := range secondRow.GetCols() {
							headers = append(headers, cel.GetString())
						}
					}
				} else {
					for _, cel := range secondRow.GetCols() {
						headers = append(headers, cel.GetString())
					}
				}
				data = append(data, headers)
			}
			log.Printf("data >>>> %+v \n", data)
			returnData[sheet.GetName()] = data
		}
	}
	if len(returnData) == 0 {
		return nil
	}
	return returnData
}

func readFromCsv(filePath string) map[string]interface{} {

	return nil
}
